package com.huakai.springenv.perf;

import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
public class PressureTestFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletRequest request1 = (HttpServletRequest) request;
            // 通过请求中的 header 判断是否为压测流量
            String pressureTestHeader = request1.getHeader("X-Pressure-Test");
            if ("true".equals(pressureTestHeader)) {
                TrafficRoutingDataSource.setPressureTestFlag(true);
            }

            chain.doFilter(request, response);
        } finally {
            // 清理 ThreadLocal
            TrafficRoutingDataSource.clearPressureTestFlag();
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void destroy() {}
}
